﻿using AntdUI;
using ImportPlcPointPosition.Models.Dto;
using ImportPlcPointPosition.Models.ViewModels;
using Mapster;
using Mapster.Utils;
using Microsoft.IdentityModel.Tokens;
using MiniExcelLibs;
using S7.Net;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZR.Model.Models.ProductionControl;

namespace ImportPlcPointPosition.Forms
{
    public partial class ImportAlarmDictForm : BaseForm
    {
        public ImportAlarmDictForm()
        {
            InitializeComponent();
            this.Load += ImportAlarmDictForm_Load;
        }

        private void ImportAlarmDictForm_Load(object sender, EventArgs e)
        {
            InitData();
        }

        private void InitData()
        {
            var db = SqlSugarHelper.MesDB;
            var lst = db.Queryable<PlcConfig>().ToList();
            List<SelectOption> plcItems = new List<SelectOption>();
            foreach (var item in lst)
            {
                plcItems.Add(new SelectOption() { Text = item.WorkstationCode, Source = item.Id });
            }
            selectPlc.Items.AddRange(plcItems.ToArray());
            selectPlc.MouseLeave += SelectPlc_MouseLeave;

            List<SelectOption> plcTypes = new List<SelectOption>();
            plcTypes.Add(new SelectOption() { Text = "西门子",Source = 0 });
            plcTypes.Add(new SelectOption() { Text = "三菱", Source = 3 });
            selectType.Items.AddRange(plcTypes.ToArray());
            selectType.SelectedIndex = 0;
            selectType.SelectedIndexChanged += SelectType_SelectedIndexChanged;
           
            
        }

        private void SelectType_SelectedIndexChanged(object sender, IntEventArgs e)
        {
            if (e.Value == 1)
                panel2.Visible = false;
            else
                panel2.Visible = true;
        }

        private void SelectPlc_MouseLeave(object sender, EventArgs e)
        {
            var item = selectPlc.SelectedValue;
            if (item != null)
            {
                selectPlc.Text = (item as SelectOption).Text;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            var plcType = (selectType.SelectedValue as SelectOption).Source.ObjToInt();
            var item1 = selectPlc.SelectedValue;
            var dbNum = txtAlarmDB.Text.ObjToInt();
            if (item1 is null)
            {
                AntdUI.Message.error(this, "请填写必填项", autoClose: 2);
                return;
            }
            if (dbNum < 1 && plcType == 0)
            {
                AntdUI.Message.error(this, "请填写必填项", autoClose: 2);
                return;
            }
            var PlcId = (item1 as SelectOption).Source.ObjToInt();

            //弹出选择报警框
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "(报警字典文件)|*.xlsx";
            var dialog = ofd.ShowDialog();
            if (dialog == DialogResult.OK)
            {
                var fname = ofd.FileName;

                AntdUI.Spin.open(this, new AntdUI.Spin.Config()
                {
                    Back = Color.FromArgb(220, 147, 181, 207),
                    Color = Style.Db.Primary,//转圈颜色

                    Radius = 6,
                    Fore = Color.Black,//字体颜色
                    Font = new Font("Microsoft YaHei UI", 14f),//字体可以控制进度圈的大小
                }, (config) =>
                {
                    try
                    {
                        config.Text = "处理中...";
                        config.Value = 0.4f;
                        if (plcType == 0)
                            ReadAndSave(dbNum, PlcId, fname);
                        else if (plcType == 3)
                            ReadAndSaveSan(PlcId,fname);
                        Thread.Sleep(500);
                    }
                    catch (Exception ex)
                    {
                        config.Value = 1.0f;
                        
                    }

                }, () =>
                {
                    DialogResult = DialogResult.OK;
                });




               

               
            }
        }
        /// <summary>
        /// 导入三菱PLC报警字典
        /// </summary>
        /// <param name="plcId"></param>
        /// <param name="fname"></param>
        private void ReadAndSaveSan(int PlcId, string fname)
        {
            var datas = MiniExcel.Query<HCImportAlarmDictDto>(fname).Adapt<List<CksAlarmDict>>();
            foreach (var item in datas)
            {

                item.AlarmCode = item.AlarmId.ToString();
                // 解析出位编号 
               // var result = ParseDbString(item.SignalAddress);
                item.BitId = item.AlarmId.ObjToInt();
                item.SignalAddress =item.SignalAddress;
                item.PlcId = PlcId;
                item.BlockDb = 0;
                item.FaultCase = item.FaultCase ?? string.Empty;
                item.Solution = item.Solution ?? string.Empty;
            }
            var db = SqlSugarHelper.MesDB;
            db.Deleteable<CksAlarmDict>().Where(a => a.PlcId == PlcId).ExecuteCommand();
            db.Insertable(datas).ExecuteCommand();
        }

        private static void ReadAndSave(int dbNum, int PlcId, string fname)
        {
            var datas = MiniExcel.Query<ImportAlarmDictDto>(fname).Adapt<List<CksAlarmDict>>();
            foreach (var item in datas)
            {

                item.AlarmCode = item.AlarmId.ToString();
                // 解析出位编号
                var result = ParseDbString(item.SignalAddress);
                item.BitId = result.Value.x * 8 + result.Value.y + 1;
                item.SignalAddress = $"DBX{result.Value.x}.{result.Value.y}";
                item.PlcId = PlcId;
                item.BlockDb = dbNum;
                item.FaultCase = item.FaultCase??string.Empty;
                item.Solution = item.Solution??string.Empty;

            }
            var tests = datas.FindAll(a => a.Solution == null);


            var db = SqlSugarHelper.MesDB;
            db.Deleteable<CksAlarmDict>().Where(a=>a.PlcId == PlcId && a.BlockDb == dbNum).ExecuteCommand();
            db.Insertable(datas).ExecuteCommand();
        }

        public static (int dbNumber, int x, int y)? ParseDbString(string input)
        {
            try
            {
                // 去除开头的%符号
                string temp = input.TrimStart('%');

                // 检查是否以DB开头
                if (!temp.StartsWith("DB"))
                {
                    return null;
                }

                // 提取DB后面的部分
                temp = temp.Substring(2);

                // 分割为DB号和后续部分
                string[] parts = temp.Split(new[] { ".DBX" }, StringSplitOptions.None);
                if (parts.Length != 2)
                {
                    return null;
                }

                // 解析DB号
                if (!int.TryParse(parts[0], out int dbNumber))
                {
                    return null;
                }

                // 分割坐标部分
                string[] coordinates = parts[1].Split('.');
                if (coordinates.Length != 2)
                {
                    return null;
                }

                // 解析X和Y坐标
                if (!int.TryParse(coordinates[0], out int x) ||
                    !int.TryParse(coordinates[1], out int y))
                {
                    return null;
                }

                return (dbNumber, x, y);
            }
            catch
            {
                return null;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
